<template>
  <div class="login relative">
    <div class="login-box">
      <div class="login-title">丽江可视化运行管理平台登录</div>
      <a-form
        :form="form"
        style="width: 320px"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-form-item label="账号" prop="loginName">
          <a-input
            v-decorator="[
              'loginName',
              { rules: [{ required: true, message: '请输入账号' }] },
            ]"
            placeholder="请输入账号"
          />
        </a-form-item>
        <a-form-item label="密码" prop="password">
          <a-input
            v-decorator="[
              'password',
              { rules: [{ required: true, message: '请输入密码' }] },
            ]"
            placeholder="请输入密码"
            type="password"
          />
        </a-form-item>
      </a-form>
      <a-spin :spinning="loading">
        <a-button type="primary" html-type="submit" @click="handleSubmit">
          登录
        </a-button>
      </a-spin>
    </div>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import router from "@/router";
import Layout from "@/layout/index.vue";
import { message } from "ant-design-vue";
import dictMixin from "@/mixins/dictMixin";
import { getOther, flattenMenuArray,AllMenuFlag } from "@/utils/routeUtil";
export default {
  mixins: [dictMixin],
  components: {
    Layout,
  },
  data() {
    return {
      loading: false,
      loginForm: {
        loginName: "",
        password: "",
      },
      tableData: [],
      form: this.$form.createForm(this, { name: "coordinated" }),
      routerData: [],
    };
  },
  methods: {
    handleSubmit() {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 15000);
      this.form.validateFields((err, values) => {
        if (!err) {
          const url = "/government-platform-center/user/login";
          const params = values;
          this.$axios
            .get(url, {
              params: params,
            })
            .then((res) => {
              if (res.data.msg == "success") {
                Cookies.set("token", res.data.data);
                const url = `/government-platform-center/user/getUserCacheByToken`;
                // const url = `/government-platform-center/user/getUserCacheByToken?token=${res.data.data}`

                this.$axios.get(url).then(async (res2) => {
                  const userInfos = JSON.parse(res2.data.data);
                  localStorage.setItem("roleId", userInfos.role.roleId);
                  Cookies.set("roleId", userInfos.role.roleId, { expires: 15 });
                  localStorage.setItem(
                    "userInfo",
                    JSON.stringify(userInfos.userInfo)
                  );
                  Cookies.set("userInfo", JSON.stringify(userInfos.userInfo), {
                    expires: 15,
                  });
                  await this.getBtn(userInfos.role.roleId);
                  const url = `/government-platform-center/menu/queryByRoleId?roleId=${userInfos.role.roleId}`;
                  this.$axios.get(url).then((res2) => {
                    if (res2.data.code == 0) {
                      localStorage.setItem(
                        "AllMenuList",
                        JSON.stringify(res2.data.data)
                      );

                      let routerTableData = [];
                      res2.data.data.forEach((ele) => {
                        // 过滤出该系统的所有菜单
                        if (AllMenuFlag.includes(ele.thisData.url)) {
                          routerTableData.push(...ele.childList);
                        }
                      });
                      const deal = getOther(routerTableData);
                      const routerData = flattenMenuArray(deal);
                      if (routerData.length > 0) {
                        let targetPath = "";
                        let isShowMenu = routerData.filter(item=>item.isHideen !== 0)

                        // 如果有工作台就先跳到工作台
                        let isControl = (isShowMenu || []).find(item=>item.path.includes('/control'))
                        if(isControl && JSON.stringify(isControl) !== '{}'){
                           targetPath = isControl.path
                        }else{
                           targetPath = isShowMenu[0].path
                        }
                      
                        router.addRoute({
                          path: "/",
                          component: Layout,
                          redirect: targetPath,
                          children: routerData,
                        });
                        this.$router.push({ path: targetPath });
                        this.loading = false;
                      } else {
                        this.$message.error("暂无权限");
                        this.loading = false;
                      }
                      this.loading = false;
                    }
                  });
                });
              } else {
                this.loading = false;
              }
            });
        }
      });
    },
    async getBtn(roleId) {
      try {
        this.loading = true;
        const url = `/government-platform-center/menu/queryFuncByRoleId?roleId=${roleId}`;
        const res = await this.$axios.get(url).finally(() => {
          this.loading = false;
        });

        if (res.data.code === 0) {
          // 过滤并格式化按钮权限数据
          const btnArr = res.data.data
            .filter((item) => item && item.url) // 过滤掉无效数据
            .map((item) => item.url);

          // 存储按钮权限
          if (btnArr.length) {
            localStorage.setItem("btnArr", JSON.stringify(btnArr));
            return btnArr; // 返回权限数组以便其他地方使用
          } else {
            console.warn("未获取到按钮权限数据");
          }
        } else {
          // 处理错误响应
          message.error(res.data.msg || "获取按钮权限失败");
        }
      } catch (error) {
        console.error("获取按钮权限出错:", error);
        message.error("获取按钮权限失败，请重试");
      }
      return []; // 发生错误时返回空数组
    },
  },
};
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: #fff;
  background: url("@/assets/bg@2x.png") no-repeat;
  background-size: 100% 100%;
}

.login-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  width: 580px;
  background: #ffffff;
  border-radius: 20px;
  padding: 70px 54px;
  box-shadow: 0px 0px 30px 0px rgba(23, 103, 222, 0.25);

  .login-title {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    margin: 20px;
  }
}

.login-form {
  width: 100%;
}

.student {
  font-size: 20px;
  color: #0364ff;
}

.admin {
  font-size: 20px;
}
</style>
